package com.example.administrator.demob;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements InOnDataChangeListener{
    private ListView lvStu;
    private Button btnAdd;
    private EditText edtKey;
    private Button btnSearch;
    private ArrayList<Student> studentArrayList =  new ArrayList<>();
    private StuAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();

       // initStuList();
        adapter = new StuAdapter(MainActivity.this,studentArrayList,
                MainActivity.this);

        readDataFromDB();


        lvStu.setAdapter(adapter);

        //编辑学生
        lvStu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,EditActivity.class);
                //向下一个活动传输数据
                Student student = studentArrayList.get(i);
                //使Student类实现Serializable接口
                intent.putExtra("STUDENT",student);
                startActivityForResult(intent, 1002);
            }
        });
    }

    /*
    * 从数据库中读取数据
    * */
    private void readDataFromDB() {
        Uri uri = Uri.parse("content://com.hjn.xn/student");

        //每次查询前要先进行清除数据
        //每次获取都需清除数组，避免重复添加
        studentArrayList.clear();

        //查询数据
        Cursor cursor = getContentResolver().query(uri,null,null,null,null);

        //若游标为空
        if(cursor != null && cursor.getCount() > 0){
            //获取查询到的列并添加到学生中
            for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                String stuNo = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student s = new Student(stuNo, name, age);
                studentArrayList.add(s);
            }
        }

        //通知adapter进行更新
        adapter.notifyDataSetChanged();
    }

    private void initStuList() {
        Student s1 = new Student("17001","Lily",20);
        Student s2 = new Student("17002","Sun",16);
        Student s3 = new Student("17003","May",22);
        studentArrayList.add(s1);
        studentArrayList.add(s2);
        studentArrayList.add(s3);
    }

    private void findViews() {
        lvStu = findViewById(R.id.lv_stu);
        btnAdd = findViewById(R.id.btn_add);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,AddActivity.class);
                startActivityForResult(intent, 1001);
            }
        });

        edtKey = findViewById(R.id.edt_key);
        btnSearch = findViewById(R.id.btn_search);
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = edtKey.getText().toString();
                search(key);
            }
        });

        //自动搜索
        edtKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String key = edtKey.getText().toString();
                search(key);
            }
        });
    }

    //搜索
    private void search(String key) {
        Uri uri = Uri.parse("content://com.hjn.xn/student");

        studentArrayList.clear();

        String where = "name like '%"+key+"%' OR stuNo like '%"+key+"%' OR age = '"+key+"'";
        Cursor cursor = getContentResolver().query(uri, null, where, null,null);

        if(cursor != null && cursor.getCount() > 0){
            for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                String stuNo = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student s = new Student(stuNo, name, age);
                studentArrayList.add(s);
            }
        }

        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode == 2001){
            String stuNo = data.getStringExtra("STUNO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE",0);

            Student s = new Student(stuNo, name, age);
            //将学生加入到学生表中
            addStuToDB(s);
        }
        else if(resultCode == 3001){
            Student student = (Student) data.getSerializableExtra("STUDENT");
            updateStudentToDB(student);
        }
    }

    //更新列表
    private void updateStudentToDB(Student student) {
        Uri uri = Uri.parse("content://com.hjn.xn/student");
        /*helper = new StuOpenHelper(MainActivity.this,"stu.db",
                null, 1);
        SQLiteDatabase db = helper.getWritableDatabase();*/

       /* //第一种：组装语句
        String sql = "update student set name='"+student.getName()+"',age='"+student.getAge()+"' where stuNo='"+student.getStuNo()+"'";
        db.execSQL(sql);
        db.close();
        readDataFromDB();*/

        //第二种：update接口
        String where = "stuNo='"+student.getStuNo()+"'";
        ContentValues values = new ContentValues();
        values.put("name", student.getName());
        values.put("age", student.getAge());
        getContentResolver().update(uri, values, where,  null);

        readDataFromDB();
    }

    private void addStuToDB(Student s) {
        Uri uri = Uri.parse("content://com.hjn.xn/student");

        ContentValues values = new ContentValues();
        values.put("stuNo",s.getStuNo());
        values.put("name",s.getName());
        values.put("age",s.getAge());
        getContentResolver().insert(uri,values);

        readDataFromDB();
    }

    //删除
    @Override
    public void del(Student student) {
        Uri uri = Uri.parse("content://com.hjn.xn/student");

       /* //第一种：组装语句
        String sql = "delete from student where stuNo = '"+student.getStuNo()+"'";
        db.execSQL(sql);
        db.close();
        readDataFromDB();*/

        /*//第二种：使用delete接口
        String where = "stuNo = '"+student.getStuNo()+"'";
        db.delete("student", where, null);
        db.close();
        readDataFromDB();*/

        //第三种：使用带参数接口
        String where = "stuNo = ? AND name = ?";
        String[] args = {student.getStuNo(), student.getName()};
        getContentResolver().delete(uri, where ,args);

        readDataFromDB();
    }
}
